package user

import (
	"context"
	"database/sql"
	"errors"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"ns/app/applet/api/internal/code"
	"ns/app/applet/api/internal/model"
	"ns/pkg/valids"
	"ns/pkg/xcode"
	"ns/pkg/xcrypt"
	"ns/pkg/xctx"
	"ns/pkg/xtypes"

	"ns/app/applet/api/internal/svc"
	"ns/app/applet/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddUserLogic {
	return &AddUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddUserLogic) AddUser(req *types.AddUserRequest) (resp *types.AddUserResponse, err error) {
	uid := xctx.GetUidFromCtx(l.ctx)
	if uid == 0 {
		return nil, xcode.NoLogin
	}
	// 校验手机号
	if valids.ValidMobile(req.Mobile) == false {
		return nil, code.ErrMobileInvalid
	}

	// 验证手机号是否已经存在
	_, err = l.svcCtx.UserModel.FindOneByMobile(l.ctx, req.Mobile)
	if err != nil {
		if !errors.Is(err, sqlx.ErrNotFound) {
			return nil, err
		}
	}
	if err == nil {
		return nil, code.ErrMobileExist
	}

	//  判断用户类型
	if !valids.ValidUserType(req.Type) {
		return nil, code.ErrUserTypeInvalid
	}
	// 判断地区等级
	if !valids.ValidAreaLevel(xtypes.AreaLevel{
		Level: int64(req.Level),
		AreaCode: xtypes.AreaCode{
			Province: req.Province,
			City:     req.City,
			Area:     req.Area,
		},
	}) {
		return nil, code.ErrAreaLevelInvalid
	}

	// 添加用户
	encryptPassword, err := xcrypt.EncryptPassword(req.Password)
	if err != nil {
		return nil, xcode.ServerErr
	}
	result, err := l.svcCtx.UserModel.Insert(l.ctx, &model.User{
		Name:     req.Name,
		Mobile:   req.Mobile,
		Email:    req.Email,
		Password: encryptPassword,
		Level:    int64(req.Level),
		Province: req.Province,
		City:     sql.NullString{String: req.City, Valid: true},
		Area:     sql.NullString{String: req.Area, Valid: true},
		Type:     req.Type,
		Status:   1,
		CreatedBy: sql.NullInt64{
			Int64: uid,
			Valid: true,
		},
	})

	if err != nil {
		return nil, err
	}

	id, err := result.LastInsertId()
	if err != nil {
		return nil, err
	}
	return &types.AddUserResponse{
		Id: id,
	}, nil
}
